<?php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
JTable::addIncludePath(JPATH_COMPONENT.DIRECTORY_SEPARATOR.'tables');

class KetnoiModelRepair extends JModelLegacy
{
	public function getTable($type = 'Repair', $prefix = 'KetnoiTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	function loadGridData($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("a.*,c.ten as tenmay,b.serial");
        $query->select("case when k.ten is null then '' else k.ten end as tenkhachhang,k.ma as makhachhang,k.id as idkhachhang");
        $query->from("#__repair a")
       		  ->innerJoin("#__inventory b on a.inventory_id = b.id")	
       		  ->innerJoin("#__products c on c.id = b.machine_id and c.product_type = 'mayphoto'")
       		  ->leftJoin("#__customer k on k.id = a.customer_id")
       		  ->order("a.id DESC");
		if(!empty($where))
        	$query->where($where);
        $query .= " limit $limitstart,$limit";  
        $db->setQuery($query);
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadAllGridData($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("a.*,c.ten as tenmay");
        $query->from("#__repair a")
       		  ->innerJoin("#__inventory b on a.inventory_id = b.id")	
       		  ->innerJoin("#__products c on c.id = b.machine_id and c.product_type = 'mayphoto'");
        if(!empty($where))
       		  $query->where($where); 
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result; 
    }
    
	function loadGridDataMaloi($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("m.ma,m.ten")
    		  ->from("#__repair_maloi rm")
    	      ->innerJoin("#__maloi m on m.id = rm.maloi_id");
    	if(!empty($where))
       		  $query->where($where);
       	$query .= " limit $limitstart,$limit";  	  
       	$db->setQuery($query);	  
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadAllGridDataMaloi($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)")
    		  ->from("#__repair_maloi rm")
    	      ->innerJoin("#__maloi m on m.id = rm.maloi_id");
    	if(!empty($where))
       		  $query->where($where);	  
       	$db->setQuery($query);	  
        $result = $db->loadResult();
        return $result; 
    }
    
	function loadGridDataNhanvien($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("p.ma,p.hoten")
    		  ->from("#__repair_employee e")
    	      ->innerJoin("#__user_profile p on p.id = e.employee_id");
    	if(!empty($where))
       		  $query->where($where);
       	$query .= " limit $limitstart,$limit";  	  
       	$db->setQuery($query);	  
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadAllGridDataNhanvien($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)")
    		  ->from("#__repair_employee e")
    	      ->innerJoin("#__user_profile p on p.id = e.employee_id");
    	if(!empty($where))
       		  $query->where($where);
       	$db->setQuery($query);	  
        $result = $db->loadResult();
        return $result; 
    }
    
	function loadGridDataLinhkien($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("a.*,d.ten as tenlinhkien,d.ma as malinhkien,b.closing,b.currentuse")
    		  ->select("case when e.ten is null then '' else e.ten end as tennhacungcap")
    		  ->select("case when e.ma is null then '' else e.ma end as manhacungcap")
    		  ->from("#__repair_linhkien_closing b")
    	      ->innerJoin("#__repair_linhkien a on b.repair_linhkien_id = a.id")
    	      ->innerJoin("#__repair c on b.repair_id = c.id")
    	      ->innerJoin("#__products d on d.id = a.linhkien_id and d.product_type='linhkien'")
    	      ->leftJoin("#__vendor e on e.id = a.vendor_id");
    	if(!empty($where))
       		  $query->where($where);
       	$query .= " limit $limitstart,$limit";  	  
       	$db->setQuery($query);	  
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadALLGridDataLinhkien($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)")
    	      ->from("#__repair_linhkien a")
    	      ->innerJoin("#__repair_linhkien_closing b on b.repair_linhkien_id = a.id")
    	      ->innerJoin("#__repair c on b.repair_id = c.id")
    	      ->innerJoin("#__products d on d.id = a.linhkien_id and d.product_type='linhkien'")
    	      ->leftJoin("#__vendor e on e.id = a.vendor_id")
    	      ->where("a.status = 0 and b.status = 0");
    	if(!empty($where))
       		  $query->where($where);
       	$db->setQuery($query);	  
        $result = $db->loadResult();
        return $result; 
    }
    
    function loadlinhkien()
    {
    	$serial = JRequest::getVar("serial");
    	$db = JFactory::getDbo();
    	$query = $db->getQuery(true);
    	$query->select("a.*,d.ten as tenlinhkien,d.ma as malinhkien,b.closing")
    		  ->select("case when e.ten is null then '' else e.ten end as tennhacungcap")
    		  ->select("case when e.ma is null then '' else e.ma end as manhacungcap")
    	      ->from("#__repair_linhkien a")
    	      ->innerJoin("#__repair_linhkien_closing b on b.repair_linhkien_id = a.id")
    	      ->innerJoin("#__repair c on b.repair_id = c.id")
    	      ->innerJoin("#__products d on d.id = a.linhkien_id and d.product_type='linhkien'")
    	      ->leftJoin("#__vendor e on e.id = a.vendor_id")
    	      ->where("a.status = 0 and b.status = 0 and c.inventory_id = $serial");
    	      
    	$db->setQuery($query);
    	return $db->loadObjectList();      
    }
    
	function save()
    {
    	global $app;
    	$result = array("success"=>true,"error"=>"");
    	$table = $this->getTable();
    	$post = JRequest::get("post");
    	date_default_timezone_set("Asia/Ho_Chi_Minh");
    	$post["datecreate"] = date("Y-m-d");
    	$post["counteruse"] = $post["socounter"];
		$table = Utility::save($table, $post);
		$result["id"] = $table->id;
		$counters = $this->updateClosing($table->inventory_id, $post["socounter"]);
		list($counter_diff,$lastuse,$currentuse) = $counters;
		$this->insertEmployee($table->id);
		$this->insertMaloi($table->id);
		$this->insertLinhkien($table->id,$lastuse,$currentuse,$counter_diff);
		$this->updateLinhkienRepair($counter_diff, $table->id, $lastuse, $currentuse);
    	return $result;
    }
	
    function updateLinhkienRepair($counter_diff,$repair_id,$lastuse,$currentuse)
    {
    	$repair_linhkien = JRequest::getVar("repair_linhkien",array());
    	$db = JFactory::getDbo();
    	foreach($repair_linhkien as $repair_lk_id)
    	{
    		$status = JRequest::getVar("theodoi_$repair_lk_id");
    		if($status == 1)
    		{
    			$query = "update #__repair_linhkien set status = 1 where id = $repair_lk_id";
    			$db->setQuery($query);
    			$db->query();
    			$query = "update #__repair_linhkien_closing set status = 1 where repair_linhkien_id = $repair_lk_id";
    			$db->setQuery($query);
    			$db->query();
    		}else
    		{
    			//get closing and supdate Closing
    			$query = "select closing from #__repair_linhkien_closing where repair_linhkien_id = $repair_lk_id and status = 0";
    			$db->setQuery($query);
    			$closing = $db->loadResult();
    			
    			$query = "update #__repair_linhkien_closing set status = 1 where repair_linhkien_id = $repair_lk_id";
    			$db->setQuery($query);
    			$db->query();
    			
    			$closing_end = $closing - $counter_diff;
    			$query = "insert into #__repair_linhkien_closing(repair_linhkien_id,repair_id,lastuse,closing,currentuse) values";
    			$query .= "($repair_lk_id,$repair_id,$lastuse,$closing_end,$currentuse)";
    			$db->setQuery($query);
    			$db->query();
    		}
    		
    	}
    }
    
	function updateClosing($inventory_id,$counter)
    {
    	$db = JFactory::getDbo();
    	$query = "select counter_current_use from #__inventory where id = $inventory_id and is_delete = 0";
    	$db->setQuery($query);
    	$lastUse = $db->loadResult();
    	$counter_diff = $counter - $lastUse;
    	$query = "update #__inventory set counter_last_use = $lastUse,counter_current_use = $counter  where id = $inventory_id";
    	$db->setQuery($query);
    	$db->query();
    	return array($counter_diff,$lastUse,$counter);
    }
    
    function insertEmployee($repair_id)
    {
    	$employees = JRequest::getVar('employee_id', array(), 'post', 'array');
		$db = JFactory::getDbo();
		$query = "insert into #__repair_employee values";
		$query_employee = array();
		foreach($employees as $employee_id)
		{
			$query_employee[] = "($repair_id,$employee_id)";
		}
		if(count($query_employee) > 0)
		{
			$query .= implode(",", $query_employee);
			$db->setQuery($query);
			$db->query();
		}
    }
    
	function insertMaloi($repair_id)
    {
    	$employees = JRequest::getVar('maloi_id', array(), 'post', 'array');
		$db = JFactory::getDbo();
		$query = "insert into #__repair_maloi values";
		$query_employee = array();
		foreach($employees as $employee_id)
		{
			$query_employee[] = "($repair_id,$employee_id)";
		}
		if(count($query_employee) > 0)
		{
			$query .= implode(",", $query_employee);
			$db->setQuery($query);
			$db->query();
		}
    }
    
	function insertLinhkien($repair_id,$lastuse,$currentuse,$counter_diff)
    {
    	$linhkiens = JRequest::getVar('linhkien_id', array(), 'post', 'array');
		
		foreach($linhkiens as $linhkien_id)
		{
			$vendor = JRequest::getVar("linhkien_vendor_$linhkien_id");
			$sothang = JRequest::getVar("sothangbaohanh_$linhkien_id");
			$sodungluong = JRequest::getVar("sodungluongbaohanh_$linhkien_id");
			$tuoitho = JRequest::getVar("tuoitho_$linhkien_id");
			$arr_tmp = array();
			$arr_tmp["linhkien_id"] = $linhkien_id;
			$arr_tmp["vendor_id"] = $vendor;
			$arr_tmp["sothangbaohanh"] = $sothang;
			$arr_tmp["sodungluongbaohanh"] = $sodungluong;
			$arr_tmp["tuoitho"] = $tuoitho;
			$table = $this->getTable("Repair_linhkien");
			$table->bind($arr_tmp);
			$table->store();
			$repair_linhkien_id = $table->id;
			
			$arr_closing = array();
			$arr_closing["repair_linhkien_id"] = $repair_linhkien_id;
			$arr_closing["repair_id"] = $repair_id;
			$arr_closing["lastuse"] = $lastuse;
			$arr_closing["currentuse"] = $currentuse;
			$arr_closing["closing"] = $tuoitho;
			$table_lk_closing = $this->getTable("Repair_linhkien_closing");
			$table_lk_closing->bind($arr_closing);
			$table_lk_closing->store();
		}
	
    }
    

	function loadAllEmployee()
	{
		$db = JFactory::getDbo();
		$query = "select p.* from #__user_profile p where p.is_delete = 0 ";
		$db->setQuery($query);
		return $db->loadObjectList();
	}
	
	function loadAllVendor()
	{
		$db = JFactory::getDbo();
		$query = "select * from #__vendor where is_delete = 0";
		$db->setQuery($query);
		return $db->loadObjectList();
	}
	
	function loadAllSerial()
	{
		$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("i.*,p.ma as ma_machine,p.ten as ten_machine");
        $query->select("case when c.ten is null then '' else c.ten end as tenkhachhang,c.ma as makhachhang,c.id as idkhachhang");
        $query->select("v.ma as ma_nhacungcap,v.ten as tennhacungcap");
        $query->from("#__inventory i")
       		  ->innerJoin("#__products p on p.id = i.machine_id")
       		  ->leftJoin("#__hopdong h on h.inventory_id = i.id and (h.status = 'dachothue' or h.status = 'daban')")
       		  ->leftJoin("#__customer c on c.id = h.customer_id")	
       		  ->leftJoin("#__vendor v on v.id = i.vendor_id")
       		  ->where("i.is_delete = 0");
        $db->setQuery($query);
        $result = $db->loadObjectList();
        return $result; 
	}
	
	function loadAllMaloi()
	{
		$db = JFactory::getDbo();
		$query = "select * from #__maloi where is_delete = 0";
		$db->setQuery($query);
		return $db->loadObjectList();
	}
}
